import { AXIS_LEFT } from './canvas-utils.js';
import { view } from './view-state.js';

const MAX_ROWS = 45;
const waterfallBuffer = [];          // 只存原始数据行，不存 ImageData
let waterfallCanvas = null;          // 专门用来存瀑布内容的离屏 canvas
let waterfallCtx = null;

export function drawWaterfall(canvas, data) {
    if (!data || data.length === 0) return;

    const ctx = canvas.getContext('2d');
    const w = canvas.width;
    const h = canvas.height;

    // === 1. 初始化离屏瀑布专用 canvas（只创建一次）===
    if (!waterfallCanvas || waterfallCanvas.width !== w || waterfallCanvas.height !== h) {
        waterfallCanvas = document.createElement('canvas');
        waterfallCanvas.width = w;
        waterfallCanvas.height = h;
        waterfallCtx = waterfallCanvas.getContext('2d', { willReadFrequently: true });
    }

    const rowH = h / MAX_ROWS;
    const colW = (w - AXIS_LEFT) / data.length;

    // === 2. 把新的一帧画到离屏 canvas 的最上面 ===
    const tempRow = new Float32Array(data);
    waterfallBuffer.push(tempRow);
    if (waterfallBuffer.length > MAX_ROWS) waterfallBuffer.shift();

    // 清空离屏 canvas 的绘图区（保留左侧 Y 轴区域不变）
    waterfallCtx.clearRect(AXIS_LEFT, 0, w - AXIS_LEFT, h);

    // 重绘所有历史行（性能足够好，因为 MAX_ROWS 只有 45）
    waterfallBuffer.forEach((row, rIdx) => {
        const y = rIdx * rowH;
        for (let i = 0; i < row.length; i++) {
            const db = row[i];
            let v = (db - view.minDb) / (view.maxDb - view.minDb);
            v = Math.max(0, Math.min(1, v));
            const intensity = Math.floor(v * 255);
            waterfallCtx.fillStyle = `rgb(${intensity}, ${255-intensity}, 0)`;
            const x = AXIS_LEFT + i * colW;
            waterfallCtx.fillRect(x, y, colW + 1, rowH + 1);
        }
    });

    // === 3. 把离屏内容一次性画到主 canvas（只画绘图区）===
    ctx.clearRect(0, 0, w, h);                    // 清主 canvas（包括左侧坐标轴区）
    ctx.drawImage(waterfallCanvas, 0, 0);         // 完整复制（左侧空白区无内容，正好留给坐标轴）

    // === 4. 重新绘制左侧 Y 轴和时间标签（永远在最上层，不会糊）===
    ctx.fillStyle = "#aaa";
    ctx.font = "11px Arial";
    ctx.textAlign = "right";
    ctx.textBaseline = "top";

    for (let i = 0; i < waterfallBuffer.length; i += 10) {
        const y = i * rowH + 4;
        const secondsAgo = (waterfallBuffer.length - 1 - i) * 0.1;  // 最新帧在最上面
        ctx.fillText(`${secondsAgo.toFixed(1)}s`, AXIS_LEFT - 8, y);
    }
    // 最上面永远显示 0.0s
    // ctx.fillText("0.0s", AXIS_LEFT - 8, 4);
}